package com.aduerr.v1shouyin.mvp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.ReportPosTotalEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.print.PrinterWrapper;
import com.aduerr.v1shouyin.unioncard.BaseUnionActivity;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.pickerview.TimePicker2View;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * 交易汇总
 */

public class TransactionActivity extends BaseUnionActivity {

    public static final String TAG = "TransactionActivity";

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.rl_timepicker)
    RelativeLayout rlTimepicker;
    @BindView(R.id.tv_shangjiashihou_count)
    TextView tvShangjiashihouCount;
    @BindView(R.id.tv_shangjiashihou_money)
    TextView tvShangjiashihouMoney;
    @BindView(R.id.dingdanjine_count)
    TextView dingdanjineCount;
    @BindView(R.id.dingdanjine_money)
    TextView dingdanjineMoney;
    @BindView(R.id.zhifubao_count)
    TextView zhifubaoCount;
    @BindView(R.id.zhifubao_money)
    TextView zhifubaoMoney;
    @BindView(R.id.weixinshoukaun_count)
    TextView weixinshoukaunCount;
    @BindView(R.id.weixinshoukaun_money)
    TextView weixinshoukaunMoney;
    @BindView(R.id.qq_count)
    TextView qqCount;
    @BindView(R.id.qq_money)
    TextView qqMoney;
    @BindView(R.id.cash_count)
    TextView cashCount;
    @BindView(R.id.cash_money)
    TextView cashMoney;
    @BindView(R.id.member_cusum_count)
    TextView memberCusumCount;
    @BindView(R.id.member_cusum_money)
    TextView memberCusumMoney;
    @BindView(R.id.yinlianshoukaun_count)
    TextView yinlianshoukaunCount;
    @BindView(R.id.yinlianshoukaun_money)
    TextView yinlianshoukaunMoney;
    @BindView(R.id.yinliantuikuan_count)
    TextView yinliantuikuanCount;
    @BindView(R.id.yinliantuikuan_money)
    TextView yinliantuikuanMoney;
    @BindView(R.id.yinlianjiejika_count)
    TextView yinlianjiejikaCount;
    @BindView(R.id.yinlianjiejika_money)
    TextView yinlianjiejikaMoney;
    @BindView(R.id.yinliandaijika_count)
    TextView yinliandaijikaCount;
    @BindView(R.id.yinliandaijika_money)
    TextView yinliandaijikaMoney;
    @BindView(R.id.shangjiayouhui_count)
    TextView shangjiayouhuiCount;
    @BindView(R.id.shangjiayouhui_money)
    TextView shangjiayouhuiMoney;
    @BindView(R.id.gaunfangyouhui_count)
    TextView gaunfangyouhuiCount;
    @BindView(R.id.gaunfangyouhui_money)
    TextView gaunfangyouhuiMoney;
    @BindView(R.id.jinridingdantuikaun_count)
    TextView jinridingdantuikaunCount;
    @BindView(R.id.jinridingdantuikaun_money)
    TextView jinridingdantuikaunMoney;
    @BindView(R.id.geridingdantuikaun_count)
    TextView geridingdantuikaunCount;
    @BindView(R.id.geridingdantuikaun_money)
    TextView geridingdantuikaunMoney;
    @BindView(R.id.hexiaojine_count)
    TextView hexiaojineCount;
    @BindView(R.id.hexiaojine_money)
    TextView hexiaojineMoney;
    @BindView(R.id.huiyauncongzhi_count)
    TextView huiyauncongzhiCount;
    @BindView(R.id.huiyauncongzhi_money)
    TextView huiyauncongzhiMoney;
    @BindView(R.id.tv_print)
    TextView tvPrint;
    @BindView(R.id.pre_permssion_count)
    TextView tvPrePermssionCount;
    @BindView(R.id.pre_permssion_money)
    TextView tvPrePermssionMoney;
    @BindView(R.id.all_refund_count)
    TextView tvAllRefundCount;
    @BindView(R.id.all_refund_money)
    TextView tvAllRefundMoney;
    @BindView(R.id.ysf_count)
    TextView tvYstCount;
    @BindView(R.id.ysf_money)
    TextView tvYstMoney;
    @BindView(R.id.pre_scan_count)
    TextView tvPreScanCount;
    @BindView(R.id.pre_scan_money)
    TextView tvPreScanMoney;

    @BindView(R.id.digital_count)
    TextView tvDigitalCount;
    @BindView(R.id.digital_money)
    TextView tvDigitalMoney;

    //打印的内容
    private String[] content = new String[42];
    private String begintime;
    private String endtime;
    private TimePicker2View pvTime2;
    private Date beginDate;
    private Date endDate;
    private int day = 0;

    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_transaction;
    }

    @Override
    protected void initBase() {
        super.initView();
        ButterKnife.bind(this);
        tvTitle.setText("交易汇总");
        getYesterdaydate();
        initTimePicker();
    }

    private void getYesterdaydate() {
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 0);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
        date = calendar.getTime();
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM" +
                "-dd");
        String dateString = formatter.format(date);

        SimpleDateFormat formatterToday = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatterToday.format(curDate);
//        Log.e(TAG, "getYesterdaydate: " + str);
        tvTime.setText(dateString + " 00:00:00" + "至" + str);
        initdate(dateString + " 00:00:00", str);
        begintime = dateString + " 00:00";
        endtime = str;

//        tvTime.setText(dateString + " 00:00" + "至" + dateString + " 23:59");
//        initdate(dateString + " 00:00:00", dateString + " 23:59:59");
//        begintime = dateString + " 00:00";
//        endtime = dateString + " 23:59";

    }

    //绑定数据
    private void initdate(String begintime, String endtime) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("begintime", begintime);
        addParams.put("endtime", endtime);
        APIRetrofit.getAPIService().getReportPosTotal(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<ReportPosTotalEntity>() {
                    @Override
                    public void onNext(ReportPosTotalEntity reportPosTotalEntity) {
                        //                    if (Tools.isAvailable
                        //                    (reportPosTotalEntity))return;
                        int success = reportPosTotalEntity.getSuccess();
                        if(success == 1) {
                            ReportPosTotalEntity.DataBean data =
                                    reportPosTotalEntity.getData();
                            if(data != null) {
                                content[0] = data.getOrdercount();
                                content[1] = data.getShishoumoney();

                                content[2] = data.getOrdercount();
                                content[3] = data.getOrdermoney();
                                //支付宝
                                content[4] = data.getAlipaycount();
                                content[5] = data.getAlipaymoney();

                                content[6] = data.getWxcount();
                                content[7] = data.getWxmoney();

                                content[8] = data.getQqcount();
                                content[9] = data.getQqmoney();

                                content[10] = data.getCashcount();
                                content[11] = data.getCashmoney();

                                content[12] = data.getMemberexcount();
                                content[13] = data.getMemberexmoney();

                                content[14] = data.getYinliancount();
                                content[15] = data.getYinlianmoney();

                                content[16] = data.getYinlianrefundcount();
                                content[17] = data.getYinlianrefundmoney();

                                content[18] = data.getYlysqcount();
                                content[19] = data.getYlysqmoney();
                          /*      content[20] = data.getYinliandaijicount();
                                content[21] = data.getYinliandaijimoney();
*/
                                content[20] = data.getDccoun();
                                content[21] = data.getDcmone();

                                content[22] = data.getSelleryouhuicount();
                                content[23] = data.getSelleryouhuimoney();

                                content[24] = data.getYouhuicount();
                                content[25] = data.getYouhuimoney();

                                /*content[26] = data.getTodaycount();
                                content[27] = data.getTodaymoney();*/

                                content[28] = data.getRefoundsumcount();
                                content[29] = data.getRefoundsummoney();

                                content[30] = data.getCardusedcount();
                                content[31] = data.getCardusedmoney();

                                content[32] = data.getMemberupcount();
                                content[33] = data.getMemberupmoney();
                                content[34] = data.getYsfcount();
                                content[35] = data.getYsfmoney();
                                content[36] = data.getSmysqcount();
                                content[37] = data.getSmysqmoney();


                                tvShangjiashihouCount.setText(data.getOrdercount());
                                tvShangjiashihouMoney.setText(data.getShishoumoney());
                                dingdanjineCount.setText(data.getOrdercount());
                                dingdanjineMoney.setText(data.getOrdermoney());
                                zhifubaoCount.setText(data.getAlipaycount());
                                zhifubaoMoney.setText(data.getAlipaymoney());
                                weixinshoukaunCount.setText(data.getWxcount());
                                weixinshoukaunMoney.setText(data.getWxmoney());
                                qqCount.setText(data.getQqcount());
                                qqMoney.setText(data.getQqmoney());
                                cashCount.setText(data.getCashcount());
                                cashMoney.setText(data.getCashmoney());
                                memberCusumCount.setText(data.getMemberexcount());
                                memberCusumMoney.setText(data.getMemberexmoney());
                                yinlianshoukaunCount.setText(data.getYinliancount());
                                yinlianshoukaunMoney.setText(data.getYinlianmoney());
                                yinliantuikuanCount.setText(data.getYinlianrefundcount());
                                yinliantuikuanMoney.setText(data.getYinlianrefundmoney());
                                yinlianjiejikaCount.setText(data.getYinlianjiejicount());
                                yinlianjiejikaMoney.setText(data.getYinlianjiejimoney());
                                yinliandaijikaCount.setText(data.getYinliandaijicount());
                                yinliandaijikaMoney.setText(data.getYinliandaijimoney());
                                shangjiayouhuiCount.setText(data.getSelleryouhuicount());
                                shangjiayouhuiMoney.setText(data.getSelleryouhuimoney());
                                gaunfangyouhuiMoney.setText(data.getYouhuimoney());
                                gaunfangyouhuiCount.setText(data.getYouhuicount());
                                jinridingdantuikaunMoney.setText(data.getTodaymoney());
                                jinridingdantuikaunCount.setText(data.getTodaycount());
                                geridingdantuikaunMoney.setText(data.getYestodaymoney());
                                geridingdantuikaunCount.setText(data.getYestodaycount());
                                tvDigitalCount.setText(data.getDccoun());
                                hexiaojineCount.setText(data.getCardusedcount());
                                hexiaojineMoney.setText(data.getCardusedmoney());
                                huiyauncongzhiCount.setText(data.getMemberupcount());
                                huiyauncongzhiMoney.setText(data.getMemberupmoney());
                                tvPrePermssionCount.setText(data.getYlysqcount());
                                tvPrePermssionMoney.setText(data.getYlysqmoney());
                                tvAllRefundCount.setText(data.getRefoundsumcount());
                                tvAllRefundMoney.setText(data.getRefoundsummoney());
                                tvYstCount.setText(data.getYsfcount());
                                tvYstMoney.setText(data.getYsfmoney());
                                tvPreScanCount.setText(data.getSmysqcount());
                                tvPreScanMoney.setText(data.getSmysqmoney());
                                tvDigitalMoney.setText(data.getDcmone());
                            }

                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(TransactionActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(TransactionActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(TransactionActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(reportPosTotalEntity.getErrMsg());
                            SharedPreferencesUtils.remove(TransactionActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(TransactionActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(TransactionActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(TransactionActivity.this,
                                    reportPosTotalEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    @OnClick({R.id.img_back, R.id.rl_timepicker, R.id.tv_print})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.rl_timepicker:
                // TODO: 2017/12/13 0013  时间控件
                pvTime2.show();
                break;
            case R.id.tv_print:
                int printpage =
                        (int) SharedPreferencesUtils.getParam(TransactionActivity.this,
                                "printpage", 1);
                if(printpage == 0) {
                    ToastUtils.showToast(TransactionActivity.this, "打印张数设置为不打印," +
                            "请先设置打印张数!!");
                    return;
                }
                content[38] = begintime;
                content[39] = endtime;
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                        R.drawable.print_public);
                print(bitmap, content, Constants.PRINT_TOTAL_ORDER, printpage);
                break;
        }
    }

    private void print(Bitmap logo, String[] content, int orderType, int printPage) {

        printOrder(logo, content, orderType, printPage);
    }

    private void printOrder(Bitmap logo, String[] content, int orderType, int printPage) {
        PrinterWrapper.printPosOrder(logo, content, orderType, printPage);
    }

    //初始化时间控件
    private void initTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(2013, 1, 23);
        final Calendar endCalendar = Calendar.getInstance();
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);//获取年份
        int month = cal.get(Calendar.MONTH);//获取月份
        int day = cal.get(Calendar.DATE);//获取日
//        endCalendar.set(year, month, day);
        int hour = cal.get(Calendar.HOUR_OF_DAY);//小时
        int minute = cal.get(Calendar.MINUTE);//分
        endCalendar.set(year, month, day, hour, minute);
//        //时间选择器

        pvTime2 = new TimePicker2View.Builder(this,
                new TimePicker2View.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v, Date date2) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                Date curDate = new Date(System.currentTimeMillis());
                if(!date2.before(curDate) || !date.before(curDate)) {//大于当前时间
                    ToastUtils.showToast(TransactionActivity.this, "时间不能大于当前时间");
                    return;
                }


                if(!date2.before(date)) {
                    try {
                        if(daysBetween(date, date2) < 5) {


                            //时间选择器
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd " +
                                    "HH:mm");
                            String formatstart = sdf.format(date);


                            StringBuffer stringBuffer = new StringBuffer();
                            begintime = sdf.format(date);
                            endtime = sdf.format(date2);
                            stringBuffer.append(begintime);
                            stringBuffer.append("至" + endtime);
                            tvTime.setText(stringBuffer.toString());


                            Calendar c = Calendar.getInstance();
                            c.setTime(date);
                            c.set(Calendar.HOUR_OF_DAY, 0);                  //把当前时间小时变成０
                            c.set(Calendar.MINUTE, 0);                      //把当前时间分钟变成０
                            c.set(Calendar.SECOND, 0);                      //把当前时间秒数变成０
                            c.set(Calendar.MILLISECOND, 0);                 //把当前时间毫秒变成０
                            beginDate = c.getTime();

                            c.setTime(date2);
                            c.set(Calendar.HOUR_OF_DAY, 23);
                            //把当前时间小时变成23
                            c.set(Calendar.MINUTE, 59);                      //把当前时间分钟变成59
                            c.set(Calendar.SECOND, 59);                      //把当前时间秒数变成59
                            c.set(Calendar.MILLISECOND, 999);
                            endDate = c.getTime();

                            //重新加载数据
                            initdate(begintime + ":00", endtime + ":59");
                        } else {
                            ToastUtils.showToast(TransactionActivity.this, "服务器限制," +
                                    "起止时间必须小于5天");
                        }

                    } catch(ParseException e) {
                        e.printStackTrace();
                        Toast.makeText(TransactionActivity.this, e.toString(),
                                Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(TransactionActivity.this,
                            getResources().getString(R.string.pickerview_choosedate_error), Toast.LENGTH_SHORT).show();
                }
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
//                .setType(new boolean[]{true, true, true, false, false, false})
                .setType(new boolean[]{true, true, true, true, true, false})
                .setLabel("年", "月", "日", "时", "分", "")
//                .setLabel("年", "月", "日", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(16)
                .setDate(selectedDate, selectedDate)
                .setRangDate(startCalendar, endCalendar, startCalendar, endCalendar)
                .setBackgroundId(0x33000000) //设置外部遮罩颜色
                .setDecorView(null)
                .setTitleText(getResources().getString(R.string.pickerview_choosedate))
                .setTitleBgColor(getResources().getColor(R.color.home_main_color))
                .setTitleColor(getResources().getColor(R.color.white))
                .setSubmitColor(getResources().getColor(R.color.white))
                .setCancelColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(android.R.color.transparent))
                .build();
    }
}
